<?php


namespace app\api\controller;


use app\admin\model\AdminLog;
use app\admin\model\express\OrderAddress;
use app\common\controller\Api;
use app\common\model\Category;
use fast\Tree;
use think\Collection;
use think\Db;
use think\Exception;
use think\exception\PDOException;

class Order extends Api
{
    protected $noNeedLogin = ['test','test1'];
    protected $noNeedRight = ['*'];

    public function test1(){
        $model = new AdminLog();
        $model->admin_id =0;
        $model->username ='a';
        $model->url ='a';
        $model->title ='a';
        $model->content = date("Y-m-d H:i:s");
        $model->content1 = date("Y-m-d H:i:s");
        $model->save();

        echo 222;die;
    }

    // 获取商品分类
    public function category(){
        $tree = Tree::instance();
        $cateArr = [];
        foreach (collection(Category::order('weigh desc,id desc')->select())->toArray() as $category){
            $cateArr[] = [
                'id' => $category['id'],
                'pid' => $category['pid'],
                'text' => $category['name']
            ];
        }
        $tree->init($cateArr, 'pid');
        $categorylist = $tree->getCateTreeArray(0);
        $this->success('ok',$categorylist);
    }

    // 创建订单
    public function addOrder(){
        if($this->request->isPost()){
            $data = $this->request->post();
            Db::startTrans();
            try {
                $address = model('app\api\model\Address')->get($data['address_id']);
                if(!$address){
                    $this->error('收货地址不存在');
                }
                $user_id = $this->auth->id;
                $order = new \app\api\model\Order();
                $order->order_no = $user_id;
                $order->user_id = $user_id;
                if($order->save()){
                    $goodsList = [];
                    foreach ($data['goods'] as $goods){
                        $validate = new \think\Validate([
                            'name|商品名称'  => 'require',
                            'category_id|分类' => 'require',
                            'brand|品牌' => 'require',
                            //'sku|规格' => 'require',
                            'weight|商品净含量' => 'require|number',
                            'number|数量' => 'require|number',
                            'price|价格' => 'float|number',
                        ]);
                        if (!$validate->check($goods)) {
                            $this->error($validate->getError());
                        }
                        $goodsList[] = [
                            'order_id' => $order->id,
                            'name' => $goods['name'],
                            'category_pid' => $goods['category_pid'],
                            'category_id' => $goods['category_id'],
                            'brand' => $goods['brand'],
                            'sku' => $goods['sku'],
                            'weight' => $goods['weight'],
                            'number' => $goods['number'],
                            'price' => $goods['price'],
                            'index' => $goods['index'],
                            'unit' => $goods['unit'] ?? 'g',
                            'description' => $goods['description'] ?? 'g',
                            'number_unit' => $goods['number_unit'] ?? '个',
                            'rule_id' => Category::where('id',$goods['category_id'])->value('rule_id')
                        ];
                    }
                    $goodsData = model('app\api\model\OrderGoods')->saveAll($goodsList);
                    //$idcard_merge = model('app\api\model\Address')->mergeIdcard($address);
                    model('app\api\model\OrderAddress')->allowField(true)->save([
                        'order_id' => $order->id,
                        'user_id' => $user_id,
                        'name' => $address['name'],
                        'mobile' => $address['mobile'],
                        'province' => $address['province'],
                        'city' => $address['city'],
                        'area' => $address['area'],
                        'address' => $address['address'],
                        'idcard' => $address['idcard'],
                        'idcard_front' => $address['idcard_front'],
                        'idcard_reverse' => $address['idcard_reverse'],
                        //'idcard_merge' => $idcard_merge,
                        'zip_code' => $address['zip_code'],
                    ]);
                    if($data['confirm'] == 1){
                        $this->inventory($order->id);
                    }
                }else{
                    $this->error(__('网络繁忙，创建订单失败！'));
                }
                Db::commit();
            }catch (\Throwable $e){
                Db::rollback();

                $model = new AdminLog();
                $model->admin_id =0;
                $model->username ='a';
                $model->url ='a';
                $model->title ='a';
                $model->content = date("Y-m-d H:i:s");
                $model->content1 = date("Y-m-d H:i:s");
                $model->save();

                $model = new AdminLog();
                $model->admin_id =0;
                $model->username ='a';
                $model->url ='a';
                $model->title ='a';
                $model->content = $e->getMessage();
                $model->content1 = $e->getTraceAsString();
                $model->save();

                $this->error($e->getMessage());
            }catch (\Throwable $e){
                Db::rollback();

                $model = new AdminLog();
                $model->admin_id =0;
                $model->username ='a';
                $model->url ='a';
                $model->title ='a';
                $model->content = date("Y-m-d H:i:s");
                $model->content1 = date("Y-m-d H:i:s");
                $model->save();

                $model = new AdminLog();
                $model->admin_id =0;
                $model->username ='a';
                $model->url ='a';
                $model->title ='a';
                $model->content = $e->getMessage();
                $model->content1 = $e->getTraceAsString();
                $model->save();
                $this->error($e->getMessage());
            }
            $this->success('ok');
        }
        $this->error('请求错误');
    }

    // 订单详情
    public function orderDetail(){
        $id = $this->request->post('id');
        $order = model('app\api\model\Order')->get($id);
        $goodsData = model('app\api\model\OrderGoods')->field('category_pid,category_id,name,brand,sku,number,price,index,weight,unit,description,number_unit')->where(['order_id'=>$id])->select();
        foreach ($goodsData as $goods){
            $goods['category_name'] = Category::where('id',$goods['category_id'])->value('name');
        }
        $goodsData = collection($goodsData)->toArray();
        $order['goods'] = $goodsData;
        $order['address'] = model('app\api\model\OrderAddress')->where('order_id',$id)->find();
        $this->success('ok',$order);
    }

    // 修改订单
    public function editOrder(){
        if($this->request->isPost()){
            $data = $this->request->post();
            Db::startTrans();
            try {
                $address = model('app\api\model\Address')->get($data['address_id']);
                if(!$address){
                    $this->error('收货地址不存在');
                }
                $user_id = $this->auth->id;
                $order = model('app\api\model\Order')->get($data['order_id']);
                if(!$order){
                    $this->error('该订单不存在');
                }
                if($order->save() !== false){
                    model('app\api\model\OrderGoods')->where('order_id',$order->id)->delete();
                    $goodsList = [];
                    foreach ($data['goods'] as $goods){
                        $goodsList[] = [
                            'order_id' => $order->id,
                            'name' => $goods['name'],
                            'category_pid' => $goods['category_pid'],
                            'category_id' => $goods['category_id'],
                            'brand' => $goods['brand'],
                            'sku' => $goods['sku'],
                            'weight' => $goods['weight'],
                            'number' => $goods['number'],
                            'price' => $goods['price'],
                            'index' => $goods['index'],
                            'unit' => $goods['unit'] ?? 'g',
                            'description' => $goods['description'] ?? 'g',
                            'number_unit' => $goods['number_unit'] ?? '个',
                            'rule_id' => Category::where('id',$goods['category_id'])->value('rule_id')
                        ];
                    }
                    $goodsData = model('app\api\model\OrderGoods')->saveAll($goodsList);
                    model('app\api\model\OrderAddress')->where('order_id',$order->id)->delete();
                    model('app\api\model\OrderAddress')->allowField(true)->save([
                        'order_id' => $order->id,
                        'user_id' => $user_id,
                        'name' => $address['name'],
                        'mobile' => $address['mobile'],
                        'province' => $address['province'],
                        'city' => $address['city'],
                        'area' => $address['area'],
                        'address' => $address['address'],
                        'idcard' => $address['idcard'],
                        'idcard_front' => $address['idcard_front'],
                        'idcard_reverse' => $address['idcard_reverse'],
                        'zip_code' => $address['zip_code'],
                    ]);
                    if($data['confirm'] == 1){
                        $this->inventory($order->id);
                    }
                }else{
                    $this->error(__('网络繁忙，创建订单失败！'));
                }
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }catch (PDOException $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('ok');
        }
        $this->error('请求错误');
    }

    //订单入库
    public function inventoryOrder(){
        $order_id = $this->request->post('order_id');
        Db::startTrans();
        try {
            $this->inventory($order_id);
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }catch (PDOException $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('ok');
    }

    // 我的订单
    public function myOrder(){
        $status = $this->request->get('status');
        $keywords = $this->request->get('keywords','');
        $where['order.user_id'] = $this->auth->id;
        if($status){
            $where['order.status'] = $status;
        }
        $list = model('app\api\model\Order')
            ->field('id,order_no,status,createtime')
            ->with(['address'])
            ->where($where)
            ->where('address.name|address.mobile|address.address|address.idcard','like','%'.$keywords.'%')
            ->order('order.createtime desc')
            ->paginate();

        foreach ($list as $row){
            $row->getRelation('address')->visible(['name','mobile','province','city','area','address','idcard','idcard_front','idcard_reverse','zip_code']);
        }
        $this->success('ok',$list);
    }

    // 我邮寄的包裹
    public function myDeliveryPackage(){
        $order_id = $this->request->get('order_id');
        $status = $this->request->get('status');
        $keywords = $this->request->get('keywords','');
        $where['package.user_id'] = $this->auth->id;
        if($order_id){
            $where['package.order_id'] = $order_id;
        }
        if($status != ''){
            $where['package.status'] = $status;
        }
        $list = model('app\api\model\Package')
            ->with(['goods','address'])
            ->where($where)
            ->where('address.name|address.mobile|address.address|address.idcard','like','%'.$keywords.'%')
            ->order('createtime desc')
            ->paginate();
        foreach ($list as $key => $row){
            $row->deliveryaddress = Db::name('express_delivery_address')->where('id',$row['delivery_address_id'])->find();
        }
        $this->success('ok',$list);
    }

    // 我接收的包裹
    public function myReceivePackage(){
        $status = $this->request->get('status');
        $keywords = $this->request->get('keywords','');
        $where['address.mobile'] = $this->auth->mobile;
        if($status != ''){
            $where['package.status'] = $status;
        }
        $list = model('app\api\model\Package')
            ->with(['goods','address'])
            ->where($where)
            ->where('address.name|address.mobile|address.address|address.idcard','like','%'.$keywords.'%')
            ->order('createtime desc')
            ->paginate();
        foreach ($list as $key => $row){
            $row->deliveryaddress = Db::name('express_delivery_address')->where('id',$row['delivery_address_id'])->find();
        }
        $this->success('ok',$list);
    }

    // 查询物流轨迹
    public function track(){
        $package_id = $this->request->get('package_id');
        $package = model('app\api\model\Package')->get($package_id);
        $trackList = [];
        $track = model('app\api\model\PackageTrack')
            ->where('package_id',$package_id)
            ->order('createtime desc')
            ->select();
        foreach ($track as $item){
            $desc = '';
            switch ($item['status']){
                case '0':
                    $desc = '包裹准备发货';
                    break;
                case '1':
                    $desc = '包裹已预报';
                    break;
                case '2':
                    $desc = '包裹发往库房';
                    break;
                case '3':
                    $desc = '库房已签收,正在处理包裹';
                    break;
                case '4':
                    $desc = '库房打包完成';
                    break;
                case '5':
                    $desc = '扫入邮袋,送往机场,等待起飞';
                    break;
                case '6':
                    $desc = '飞往中国';
                    break;
                case '7':
                    $desc = '到达中国';
                    break;
                case '8':
                    $desc = '清关中';
                    break;
                case '9':
                    $desc = '发送国内快递';
                    break;
            }
            $trackList[] = [
                'desc' => date('Y-m-d H:i:s',$item['createtime']),
                'text' => $desc,
            ];
        }
        if($package['status'] == '9'){
            $trackList[] = [
                'desc' => $package['express_com'].$package['express_no'],
                'text' => '国内快递单号',
            ];
            $express = model('app\api\model\Subscribe')
                ->where(['express_no' => $package['express_no']])
                ->find();
            if($express){
                $expressList = json_decode($express['data'], true);
                foreach ($expressList as $item){
                    $trackList[] = [
                        'desc' => $item['time'],
                        'text' => $item['context'],
                    ];
                }
            }else{
                $trackList[] = [
                    'text' => '打包完成，正在等待快递小哥揽收~',
                    'desc' => date('Y-m-d H:i:s',model('app\api\model\PackageTrack')
                        ->where('package_id',$package_id)
                        ->where('status','9')
                        ->value('createtime'))
                ];
            }
        }
        $this->success('ok',$trackList);
    }

    // 包裹详情
    public function packageDetail(){

        $package_id = $this->request->post('package_id');
        $detail = model('app\api\model\Package')
            ->field('id,package_no,express_com,express_no,delivery_price,delivery_time,status,delivery_address_id,createtime')
            ->with(['goods','address'])
            ->where('package.id',$package_id)
            ->find();
        if(!$detail){
            $this->error('该包裹不存在');
        }
        $detail->deliveryaddress = Db::name('express_delivery_address')->where('id',$detail['delivery_address_id'])->find();
        $this->success('ok',$detail);
    }

    // 入库操作
    public function inventory($order_id){
        $order = model('app\api\model\Order')->get($order_id);
        $goodsData = model('app\api\model\OrderGoods')->where(['order_id'=>$order_id])->select();
        $goodsData = collection($goodsData)->toArray();
        $ruleList = model('app\admin\model\express\Rule')->all();
        $packageModel = new \fast\Package($goodsData,$ruleList);
        $packageList = $packageModel->buildPackage();
        $packageGoodsList = $packageTrackData = [];
        $list = [];
        foreach ($packageList as $item){
            $list = array_merge($list,$item);
        }
        $num = 1;
        if($list){
            foreach ($list as $key => $val){
                $package = new \app\admin\model\express\Package();
                $package->order_id =  $order->id;
                $package->user_id = $order->user_id;
                $package->address_id = OrderAddress::where([
                    'user_id' => $order->user_id,
                    'order_id' => $order->id,
                ])->value('id');
                $package->delivery_address_id = Db::name('express_delivery_address')->where('status','normal')->orderRaw('rand()')->value('id');
                $package->package_no = $order->order_no.'-'.($num);
                $num++;
                if($package->save()){
                    foreach ($val['goods'] as $packageGoods){
                        $goods = model('app\api\model\OrderGoods')->get($packageGoods['id']);
                        $packageGoodsList[] = [
                            'package_id' => $package->id,
                            'order_id' => $order->id,
                            'category_pid' => $goods['category_pid'],
                            'category_id' => $goods['category_id'],
                            'name' => $goods['name'],
                            'brand' => $goods['brand'],
                            'sku' => $goods['sku'],
                            'weight' => $goods['weight'],
                            'number' => $packageGoods['order_goods_number'],
                            'price' => $goods['price'],
                            'rule_id' => $goods['rule_id'],
                            'unit' =>  $goods['unit'] ?? 'g',
                            'description' =>  $goods['description'],
                            'number_unit' => $goods['number_unit'],
                        ];
                    }
                    $packageTrackData[] = [
                        'package_id' => $package->id,
                        'memo' => '准备发货',
                        'admin_id' => 0,
                    ];
                }else{
                    throw new Exception("包裹添加失败");
                }
            }
            $res = model('app\admin\model\express\PackageGoods')->saveAll($packageGoodsList);
            if(empty($res)){
                throw new Exception("包裹商品添加失败");
            }
            $res= model('app\admin\model\express\PackageTrack')->saveAll($packageTrackData);
            if(empty($res)){
                throw new Exception("包裹轨迹添加失败");
            }

            $params = [
                'status' => 'package',
                'delivery_price' => 0,
            ];
            $order->allowField(true)->save($params);
        }

        return true;
    }

    // 入库操作11
    public function test(){
        $order_id = (int)$this->request->param('order_id');
        $order = model('app\api\model\Order')->get($order_id);
        if(empty($order)){
            $this->error("订单不存在");
        }

        $goodsData = model('app\api\model\OrderGoods')->where(['order_id'=>$order_id])->select();
        $goodsData = collection($goodsData)->toArray();
        dump($goodsData);
        $ruleList = model('app\admin\model\express\Rule')->all();
        $ruleList = collection($ruleList)->toArray();
        dump($ruleList);
        $packageModel = new \fast\Package($goodsData,$ruleList);
        $packageList = $packageModel->buildPackage();

        dump($packageList);die;
        $packageGoodsList = $packageTrackData = [];
        $list = [];
        foreach ($packageList as $item){
            $list = array_merge($list,$item);
        }



        $num = 1;
        foreach ($list as $key => $val){
            $package = new \app\admin\model\express\Package();
            $package->order_id =  $order->id;
            $package->user_id = $order->user_id;
            $package->address_id = OrderAddress::where([
                'user_id' => $order->user_id,
                'order_id' => $order->id,
            ])->value('id');
            $package->delivery_address_id = Db::name('express_delivery_address')->where('status','normal')->orderRaw('rand()')->value('id');
            $package->package_no = $order->order_no.'-'.($num);
            $num++;
            if($package->save()){
                foreach ($val['goods'] as $packageGoods){
                    $goods = model('app\api\model\OrderGoods')->get($packageGoods['id']);
                    $packageGoodsList[] = [
                        'package_id' => $package->id,
                        'order_id' => $order->id,
                        'category_pid' => $goods['category_pid'],
                        'category_id' => $goods['category_id'],
                        'name' => $goods['name'],
                        'brand' => $goods['brand'],
                        'sku' => $goods['sku'],
                        'weight' => $goods['weight'],
                        'number' => $packageGoods['order_goods_number'],
                        'price' => $goods['price'],
                        'rule_id' => $goods['rule_id'],
                        'unit' =>  $goods['unit'] ?? 'g',
                        'description' =>  $goods['description'],
                        'number_unit' => $goods['number_unit'],
                    ];
                }
                $packageTrackData[] = [
                    'package_id' => $package->id,
                    'memo' => '准备发货',
                    'admin_id' => 0,
                ];
            }
        }

        model('app\admin\model\express\PackageGoods')->saveAll($packageGoodsList);
        model('app\admin\model\express\PackageTrack')->saveAll($packageTrackData);
        $params = [
            'status' => 'package',
            'delivery_price' => 0,
        ];
        $order->allowField(true)->save($params);
    }

    // 订单删除
    public function del(){
        $order_id = $this->request->post('order_id');
        $row = model('app\api\model\Order')->where([
            'id' => $order_id,
            'user_id' => $this->auth->id
        ])->find();
        if(!$row){
            $this->error('该订单不存在');
        }
        if($row['inventory_status'] == 1){
            $package = model('app\admin\model\express\Package')->where('order_id',$order_id)->find();
            if($package){
                model('app\admin\model\express\PackageGoods')->where('package_id',$package['id'])->delete();
            }
            model('app\admin\model\express\Package')->where('order_id',$order_id)->delete();
        }
        $res = model('app\api\model\Order')->where('id',$order_id)->delete();
        if($res){
            $this->success();
        }else{
            $this->error('订单删除失败');
        }
    }

    // 包裹删除
    public function packageDel(){

        $package_id = $this->request->post('package_id');
        $package = model('app\api\model\Package')->where([
            'id' => $package_id,
            'user_id' => $this->auth->id
        ])->find();
        if(!$package){
            $this->error('包裹不存在');
        }
        if($package){
            model('app\api\model\Order')->where('id',$package['order_id'])->update([
                'inventory_status' => 0,
                'status' => 'created'
            ]);
            model('app\admin\model\express\PackageGoods')->where('package_id',$package['id'])->delete();
        }
        $res = model('app\api\model\Package')->where('id',$package_id)->delete();
        if($res){
            $this->success();
        }else{
            $this->error('包裹删除失败');
        }
    }
    // 搜索之前填入的商品详细信息
    public function searchGoodsInfo(){
        $field = $this->request->param('field');
        $keywords = $this->request->param('keywords');
        if(!$keywords){
            $this->success('ok',[]);
        }
        $list = model('app\api\model\OrderGoods')
            ->group($field)
            ->where($field,'like','%'.$keywords.'%')->column($field);
        $this->success('ok',$list);
    }
}

